import self

codec = 'utf-8'
import sys
import pygame
from .utils import *
from .Sprites import *

'''打砖块游戏'''
class breakoutClone():
    def __init__(self, cfg, **kwargs):
        pygame.init()  # pygame.init（）初始化所有导入的pygame模块
        pygame.display.set_caption('打砖头游戏')  # 可视化界面显示主题
        pygame.mixer.init()  # pygame.mixer.init  —  初始化混音器模块，后续音乐播放准备
        self.screen = pygame.display.set_mode((cfg.SCREENWIDTH, cfg.SCREENHEIGHT)) #创建窗口
        self.font_small = pygame.font.Font(cfg.FONTPATH, 20)
        self.font_big = pygame.font.Font(cfg.FONTPATH, 30)
        self.hit_sound = pygame.mixer.Sound(cfg.HITSOUNDPATH)
        # pygame.mixer.Sound：从文件或缓冲区对象创建新的Sound对象
        pygame.mixer.music.load(cfg.BGMPATH)  # 背景音乐
        pygame.mixer.music.play(-1, 0.0)#第一个参数表示无限循环，第二个参数表示从0.0开始
        self.cfg = cfg

    '''运行游戏'''
    def run(self):
        while True:
            #开始界面
            self.__startInterface()
            for idx, levelpath in enumerate(self.cfg.LEVELPATHS):

                state = self.__runLevel(levelpath)

                if idx == len(self.cfg.LEVELPATHS) - 1:
                    break
                if state == 'win':  #胜利则下一关
                    self.__nextLevel()
                else:
                    break
            if state == 'fail':
                self.__endInterface(False)
            else:
                self.__endInterface(True)

    '''运行某关卡'''
    def __runLevel(self, levelpath):

        score = 0
        num_lives = 2   #游戏次数
        # running: 游戏正在进行, fail: 游戏失败, win: 游戏成功.
        state = 'running'
        #球和板子放的位置
        paddle = Paddle((self.cfg.SCREENWIDTH - self.cfg.PADDLEWIDTH) / 2,
                        self.cfg.SCREENHEIGHT - self.cfg.PADDLEHEIGHT - 10, self.cfg.PADDLEWIDTH, self.cfg.PADDLEHEIGHT,
                        self.cfg.SCREENWIDTH, self.cfg.SCREENHEIGHT)
        ball = Ball(paddle.rect.centerx - self.cfg.BALLRADIUS, paddle.rect.top - self.cfg.BALLRADIUS * 2,
                    self.cfg.BALLRADIUS, self.cfg.SCREENWIDTH, self.cfg.SCREENHEIGHT)
        #创建精灵
        brick_sprites = pygame.sprite.Group()
        brick_positions = loadLevel(levelpath)

        for bp in brick_positions:
            #放置砖块
            brick_sprites.add(Brick(bp[0] * self.cfg.BRICKWIDTH, bp[1] * self.cfg.BRICKHEIGHT, self.cfg.BRICKWIDTH,
                                    self.cfg.BRICKHEIGHT))
        clock = pygame.time.Clock()  # 创建时钟对象 (可以控制游戏循环频率）

        while True:
            if state != 'running':
                return state
            for event in pygame.event.get():    # 监听用户事件
                if event.type == pygame.QUIT:   # 判断用户是否点击了关闭按钮
                    pygame.quit()   # 卸载所有pygame模块
                    sys.exit(-1)    # 直接终止当前正在执行的Python程序
            keys_pressed = pygame.key.get_pressed()
            if keys_pressed[pygame.K_LEFT]:
                paddle.move('left')
            elif keys_pressed[pygame.K_RIGHT]:
                paddle.move('right')
            self.screen.fill(self.cfg.AQUA)
            is_alive = ball.move()

            # 判断有没有接住球
            if not is_alive:
                ball.reset()    # 重置
                paddle.reset()
                num_lives -= 1
                if num_lives == 0:
                    state = 'fail'
            # 球和砖块碰撞检测
            # 参数中的true代表说发生碰撞的brick_sprites将从group组移除
            num_bricks = pygame.sprite.spritecollide(ball, brick_sprites, True)
            score += len(num_bricks)
            # 球和拍碰撞检测
            if pygame.sprite.collide_rect(ball, paddle):
                ball.change()
            # 判断砖块是否已经打完
            if len(brick_sprites) == 0:
                state = 'win'

            # 将游戏精灵绑定到屏幕
            paddle.draw(self.screen, self.cfg.PURPLE)
            ball.draw(self.screen, self.cfg.WHITE)

            for brick in brick_sprites:
                brick.draw(self.screen, self.cfg.YELLOW)

            text_render = self.font_small.render('SCORE: %s, LIVES: %s' % (score, num_lives), False, self.cfg.BLUE)
            self.screen.blit(text_render, (10, 10))
            pygame.display.flip()
            clock.tick(50)

    '''关卡切换'''
    def __nextLevel(self):
        clock = pygame.time.Clock()  # 创建时钟对象 (可以控制游戏循环频率）
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit(-1)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
                    return

            self.screen.fill(self.cfg.AQUA)
            text = 'click <Enter> to enter the next level'
            text_render = self.font_big.render(text, False, self.cfg.BLUE)
            self.screen.blit(text_render, ((self.cfg.SCREENWIDTH - text_render.get_rect().width) // 2,
                                           (self.cfg.SCREENHEIGHT - text_render.get_rect().height) // 3))
            pygame.display.flip()
            clock.tick(30)

    '''开始界面'''
    def __startInterface(self):
        clock = pygame.time.Clock() # 创建时钟对象
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                    pygame.quit()
                    sys.exit(-1)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
                    return
            self.screen.fill(self.cfg.AQUA)
            text1 = "click <Enter> to start the game"
            text2 = "click <Esc> to end the game"
            #字体颜色渲染
            text_render1 = self.font_big.render(text1, False, self.cfg.BLUE)
            text_render2 = self.font_big.render(text2, False, self.cfg.BLUE)
            #将字体放在屏幕上
            self.screen.blit(text_render1, ((self.cfg.SCREENWIDTH - text_render1.get_rect().width) // 2,
                                            (self.cfg.SCREENHEIGHT - text_render1.get_rect().height) // 4))
            self.screen.blit(text_render2, ((self.cfg.SCREENWIDTH - text_render2.get_rect().width) // 2,
                                            (self.cfg.SCREENHEIGHT - text_render2.get_rect().height) // 2))
            pygame.display.flip()

            clock.tick(30)

    '''结束界面'''
    def __endInterface(self, is_win):
        if is_win:
            text1 = 'Congratulations! You win!'
        else:
            text1 = 'Game Over! You fail!'
        text2 = "click <R> to continue the game"
        text3 = "click <Esc> to end the game"
        clock = pygame.time.Clock()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                    pygame.quit()
                    sys.exit(-1)
                if event.type == pygame.KEYDOWN and event.key == pygame.K_r:
                    return
            self.screen.fill(self.cfg.AQUA)
            text_render1 = self.font_big.render(text1, False, self.cfg.BLUE)
            text_render2 = self.font_big.render(text2, False, self.cfg.BLUE)
            text_render3 = self.font_big.render(text3, False, self.cfg.BLUE)
            self.screen.blit(text_render1, ((self.cfg.SCREENWIDTH - text_render1.get_rect().width) // 2,
                                            (self.cfg.SCREENHEIGHT - text_render1.get_rect().height) // 4))
            self.screen.blit(text_render2, ((self.cfg.SCREENWIDTH - text_render2.get_rect().width) // 2,
                                            (self.cfg.SCREENHEIGHT - text_render2.get_rect().height) // 2))
            self.screen.blit(text_render3, ((self.cfg.SCREENWIDTH - text_render3.get_rect().width) // 2,
                                            (self.cfg.SCREENHEIGHT - text_render2.get_rect().height) // 1.5))
            #更新整个显示的内容
            pygame.display.flip()

            clock.tick(30)
